

import sys, os, codecs, time
import subprocess as sp
from Tkinter import *
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch, cm
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
styles = getSampleStyleSheet()

sys.path.append('Software/pybarcode')

from barcode import get_barcode, get_barcode_class, __version__
try:
    from barcode.writer import ImageWriter
except ImportError:
    ImageWriter = None
    print 'ImageWriter=none'
    
class main():
    def __init__(self, parent, root):    
        self.code = 'code39'
        self.dh = parent.dh
        self.boothPath = parent.boothPath
        self.barcodePath = parent.barcodePath
        self.root = root
        self.root.title('Generate Barcodes From Inventory')
        self.booth = StringVar()      
        self.item = StringVar()
        self.item.set('0')
        self.toprint = []
        self.status = StringVar()
        self.status.set('Enter booth and item # to print one, leave item # 0 to print all in booth\nEnter as many codes as desired and then click Print to generate pdf')
        
        boothLabel = Label(self.root, text='Booth #: ').grid(row=0,column=0)
        boothEntry = Entry(self.root, textvariable=self.booth,width=5)
        boothEntry.grid(row=0,column=2,sticky=E)
        boothEntry.bind('<Return>',self.gen_bcodes)
        boothEntry.bind('<KP_Enter>',self.gen_bcodes)
        itemLabel =  Label(self.root, text='Item #: ').grid(row=1,column=0)
        itemEntry = Entry(self.root, textvariable=self.item,width=5).grid(row=1,column=2,sticky=E)
        statLabel = Label(self.root, textvariable=self.status).grid(row=2,column=0,columnspan=3)

        genButton = Button(self.root,text='Add Code(s)',width=14,command=self.gen_bcodes).grid(row=3,column=2)
        printButton = Button(self.root,text='Print',width=14,command=self.layoutPrint).grid(row=3,column=1)
        self.listbox = Listbox(self.root,width=60,height=30)
        self.listbox.grid(row=4,column=0,columnspan=3)
        finButton = Button(self.root, text='Done',width=14,command=self.finalize).grid(row=5,column=2)
    
   
    def gen_bcodes(self, event=None):
        
        def write(incode,text):
            if ImageWriter is not None:
                bcodec = get_barcode_class(self.code)
                bcode = bcodec(incode, writer=ImageWriter(text),add_checksum=False)
                opts = dict(font_size=14, text_distance=1)
                print 'writing %s' % incode
            if self.code.startswith('i'):
                opts['center_text'] = False
            else:
                opts['center_text'] = True
                
            filename = bcode.save(os.path.join(self.barcodePath, incode), opts)
            self.toprint.append(filename)
            self.listbox.insert(END,incode)
        try:    
            item = self.item.get()
            booth = self.booth.get()
            if item != '0':
                _item = self.dh.cons_dict[booth].item_dict[item]
                
                
                booth = int(_item.owner_number)
                item = int(_item.item_number)
                price = float(_item.original_price)
                
                incode = '%i  %i    %i' % (booth,item,price*100)
                date = time.strftime("%m/%d/%y")
                text = '%s %i %i, $%.2f' % (date,booth,item,price)
                write(incode,text)
                
                
            elif item == '0':
                cons = self.dh.cons_dict[booth]
                for item_key in cons.item_dict.keys():
                    _item = cons.item_dict[item_key]
                    item = _item.item_number
                    consignor = _item.owner
                    booth = _item.owner_number
                    price = _item.original_price
                    cons_date = _item.consign_date    
                    booth = int(booth)
                    item = int(item)
                    price = float(price)
                    incode = '%i  %i    %i' % (booth,item,price*100)
                    date = time.strftime("%m/%d/%y")
                    text = '%s %i %i, $%.2f' % (date,booth,item,price)
                    write(incode,text)
            
            self.status.set('Barcodes added to print list.\nContinue adding additional codes or press Print to finish')
        except:
            self.status.set('ERROR: Booth not found')

    
    def layoutPrint(self):
        timestamp = time.localtime()
        pdfPath = os.path.join(self.barcodePath, '%s_%s.pdf' % (timestamp.tm_mon, timestamp.tm_year))
        c = canvas.Canvas(pdfPath,pagesize=letter)
        width,height=letter
        aspectRatio = (662/241.)
        imh = 1.2*inch
        imw = 2.77*inch
     
        i = 0
        j = 0
        for item in self.toprint:
            if i%3 == 0:
                i = 0
                j+= 1
            h_origin = i*imw + 0.1*inch
            v_origin = height - j*imh + 0.25
            if v_origin <= 0:
                c.save()
            c.drawImage(item, h_origin, v_origin, imw, imh)
            os.remove(item)
            i+=1
        c.save()
        self.toprint = []
        sp.call(['gnome-open',pdfPath])

    
    def finalize(self):
        self.root.destroy()
    
def start(parent,root):
    ins = main(parent,root)
